package org.huang.sample10.config.support;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * @描述：MybatisConfigurationSupport类描述
 * @作者: huanganwei
 * @创建时间: 2021-07-31 00:59:06
 * @版本: 1.0
 */
public class MybatisConfigurationSupport {

    /**
     * 通过mybatis的配置属性和dataSource，构建SqlSessionFactory
     * @param mybatisProperties
     * @param dataSource
     * @return
     * @throws IOException
     */
    public static SqlSessionFactory sqlSessionFactoryOf(MybatisProperties mybatisProperties, DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        if(!ObjectUtils.isEmpty(mybatisProperties.resolveMapperLocations())){
            factoryBean.setMapperLocations(mybatisProperties.resolveMapperLocations());
        }

        if(StringUtils.hasText(mybatisProperties.getConfigLocation())){
            Resource resource  =  new PathMatchingResourcePatternResolver().getResource(mybatisProperties.getConfigLocation());
            factoryBean.setConfigLocation(resource);
        }

        if(StringUtils.hasText(mybatisProperties.getTypeAliasesPackage())){
            factoryBean.setTypeAliasesPackage(mybatisProperties.getTypeAliasesPackage());
        }

        if(StringUtils.hasText(mybatisProperties.getTypeHandlersPackage())){
            factoryBean.setTypeHandlersPackage(mybatisProperties.getTypeHandlersPackage());
        }

        return factoryBean.getObject();
    }
}
